package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.QuestionTagMapper;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.mapper.UserQuestionMapper;
import cn.tedu.knows.portal.model.*;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.service.ITagService;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.QuestionVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private UserQuestionMapper userQuestionMapper;
    @Autowired
    private IUserService userService;
    @Override
    public PageInfo<Question> getMyQuestion(String username,Integer pageNum,Integer pageSize) {
        User user =userMapper.findUserByUsername(username);
        QueryWrapper<Question> query=new QueryWrapper<>();
        query.eq("user_id",user.getId());
        query.eq("delete_status",0);
        query.orderByDesc("createtime");
        PageHelper.startPage(pageNum,pageSize);
        List<Question> list=questionMapper.selectList(query);
       for (Question q:list){
           List<Tag> tags=tagNamesToTags(q.getTagNames());
           q.setTags(tags);
       }
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public void saveQuestion(QuestionVo questionVo, String username) {
        User user=userMapper.findUserByUsername(username);
        StringBuilder builder=new StringBuilder();
        for (String tagName:questionVo.getTagNames()){
            builder.append(tagName).append(",");
        }
        String tagNames=builder.deleteCharAt(builder.length()-1).toString();
        Question question=new Question()
                .setTitle(questionVo.getTitle())
                .setContent(questionVo.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        int num =questionMapper.insert(question);
        if (num!=1){
            throw new ServiceException("数据库忙！");
        }
        Map<String,Tag> tagMap=tagService.getTagMap();
        for (String tagName:questionVo.getTagNames()) {
            Tag t =tagMap.get(tagName);
            QuestionTag questionTag =new QuestionTag()
                    .setQuestionId(question.getId())
                    .setTagId(t.getId());
            num=questionTagMapper.insert(questionTag);
            if (num!=1){
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和标签的关系：{}",questionTag);
        }
        Map<String,User> teacherMap=userService.getTeacherMap();
        for (String nickname: questionVo.getTeacherNicknames()) {
            User teacher=teacherMap.get(nickname);
            UserQuestion userQuestion=new UserQuestion()
                    .setQuestionId(question.getId())
                    .setUserId(teacher.getId())
                    .setCreatetime(LocalDateTime.now());
            num =userQuestionMapper.insert(userQuestion);
            if (num!=1){
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和讲师的关系：{}",userQuestion);
        }
    }

    @Override
    public PageInfo<Question> getTeacherQuestions(String username, Integer pageNum, Integer pageSize) {
        User user=userMapper.findUserByUsername(username);
        PageHelper.startPage(pageNum,pageSize);
        List<Question> list =questionMapper.findTeacherQuestions(user.getId());
        for (Question q:list){
            List<Tag> tags=tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }
        return new PageInfo<>(list);
    }

    @Autowired
    private ITagService tagService;
    private List<Tag> tagNamesToTags(String tagNames) {
        String[] names=tagNames.split(",");
        Map<String,Tag> tagMap =tagService.getTagMap();
        List<Tag> tags=new ArrayList<>();
        for (String name:names){
            Tag t=tagMap.get(name);
            tags.add(t);
        }
        return tags;
    }

}
